<?php

class Application_Model_DbTable_ZFSunsetImages extends Zend_Db_Table_Abstract {

    protected $_name = 'zf_sunset';

    public function getAllEvenApprovedSunsets($country) {
        #	Return only multipled 2 records
        $select = $this->_db->select()
                        ->from($this->_name, array('image', 'location'))
                        ->where('approved = ?', 1)
                        ->where('country_o_r = ?', $country)
                        ->order('RAND()');
        $resultsForCountry = $this->getAdapter()->fetchAll($select);
        $resultsForCountry = $this->randomizePictures($resultsForCountry);
#Zend_Debug::dump($resultsForCountry, '$resultsForCountry');
        $select = $this->_db->select()
                        ->from($this->_name, array('image', 'location'))
                        ->where('approved = ?', 1)
                        ->where('country_o_r != ?', $country)
                        ->order('RAND()');
        $resultsForAllButCountry = $this->getAdapter()->fetchAll($select);
        $resultsForAllButCountry = $this->randomizePictures($resultsForAllButCountry);

        $results = $this->mergeResults($resultsForCountry, $resultsForAllButCountry);
        // addEmptyElement for dropdowns
#Zend_Debug::dump($resultsForAllButCountry, '$resultsForAllButCountry');
        $imagesNumber = count($results);
        if ($imagesNumber > 80) {
            for ($imagesNumber; $imagesNumber > 80; $imagesNumber--) {
                $tooMuch = array_pop($results);
            }
        } else {
            $deleteElements = $imagesNumber % 2;
            if ($deleteElements > 0) {
                for ($i = 1; $i <= $deleteElements; $i++) {
                    $tooMuch = array_pop($results);
                }
            }
        }

        return $results;

        /*
          ->fetchAll($select);
          [0] => array(2) {
          ["code_country"] => string(2) "CA"
          ["name_en"] => string(6) "Canada"
          }
          [1] => array(2) {
          ["code_country"] => string(2) "FR"
          ["name_en"] => string(6) "France"
          }
         */
        #->fetchRow($select);
        /*
          ->fetchPairs($select);
          ["CA"] => string(6) "Canada"
          ["FR"] => string(6) "France"
          ["BR"] => string(6) "Brazil"
         */
    }

    private function randomizePictures($picturesArr) {
        foreach ($picturesArr as $key => $value) {
            $picturesArr[$key]['sunset_id'] = rand(1, 999999);
        }
        $picturesArr = $this->sortImagesArray($picturesArr, $order = "ASC");
        return $picturesArr;
    }

    private function mergeResults($mainCountryArr, $restArr) {
        foreach ($restArr as $key => $value) {
            $mainCountryArr[] = $value;
        }
        return $mainCountryArr;
    }

    public function getAllUnapprovedSunsetsForCountry($country) {
        $select = $this->_db->select()
                        ->from($this->_name, array('sunset_id', 'name', 'location', 'image', 'email'))
                        ->where('approved = ?', 0)
                        ->where('country_o_r = ?', $country)
                        ->order('upload_date ASC');
        $results = $this->getAdapter()->fetchAll($select);
        // addEmptyElement for dropdowns
        return $results;
    }

    public function getLastInsertId() {
        return $this->_db->lastInsertId();
    }

    //This MF will return true if the record with id is already in db.
    public function checkRecordId($id) {
        $select = $this->_db->select()
                        ->from($this->_name, array('sunset_id', 'location'))
                        ->where('sunset_id = ?', $id);
        $results = $this->getAdapter()->fetchPairs($select);
        if (count($results) >= 1) {
            return false;
        } else {
            return true;
        }
    }

    public function getImageDetails($image) {
        $select = $this->_db->select()
                        ->from($this->_name, array('name', 'location', 'image'))
                        ->where('image = ?', $image);
        $results = $this->getAdapter()->fetchRow($select);
        return $results;
    }

    public function setApproveForImages($images, $market) {
        foreach ($images as $elem => $id) {
            $q_sessions = "UPDATE zf_sunset SET approved=1, approved_by = $market WHERE sunset_id = $id";
            $this->_db->query($q_sessions);
        }
    }

    public function deletePictures($picturesArray) {
        foreach($picturesArray as $key => $value) {
            $where = "sunset_id = $value";
            $this->delete($where);
        }
    }

    public function getAllApprovedImagesForCountries($countriesArray, $order = "ASC") {
        $result = array();
        foreach ($countriesArray as $key => $value) {
            $select = $this->_db->select()
                            ->from($this->_name, array('sunset_id', 'name', 'location', 'image', 'email', 'country_o_r'))
                            ->where('approved = ?', 1)
                            ->where('country_o_r = ?', $value["code_country"])
                            ->order('sunset_id ASC');
            $results = $this->getAdapter()->fetchAll($select);
            foreach ($results as $inkey => $invalue) {
                $invalue['cname'] = $value['cname'];
                $result[] = $invalue;
            }
            #Zend_Debug::dump($result, '$result');
        }
        $result = $this->sortImagesArray($result, $order);
        return $result;
    }

    private function sortImagesArray($articlesArray, $order = "ASC") {
        $sortedArray = array();
        foreach ($articlesArray as $key => $value) {
            $sortedArray[$key] = $value["sunset_id"];
        }
        sort($sortedArray);
#        Zend_Debug::dump($sortedArray, '$sortedArray');

        if ($order == "DESC") {
            sort($sortedArray);
        } else {
            rsort($sortedArray);
        }
        #    array_reverse($sortedArray);

        foreach ($sortedArray as $key => $value) {
            foreach ($articlesArray as $inkey => $invalue) {
                if ($value == $invalue["sunset_id"]) {
                    $sortedArray[$key] = $invalue;
                }
            }
        }
        return $sortedArray;
    }

}